<?php

namespace app\im\service;

use think\swoole\Websocket;
use think\swoole\websocket\Room;

class Ws
{
    protected ?Websocket $ws = null;
    protected ?Room $room = null;
    protected int $appid;
    public function __construct(Websocket $websocket = null, Room $room = null, int $appid = 1)
    {
        if ($websocket) $this->ws = $websocket;
        if ($room) $this->room = $room;
        $this->appid = $appid;

    }

    /**
     * 检查用户是否在特定房间
     * @param $room_name
     * @return bool
     */
    public function checkUserInRoom($room_name): bool
    {
        $rooms= $this->room->getRooms($this->ws->getSender());
        if(in_array($this->appid.'_'.$room_name,$rooms))return true;
        return false;
    }
    /**
     * 检查用户是否登录绑定
     * @return bool
     */
    public function checkUserLogin(): bool
    {
        return $this->checkUserInRoom($this->appid.'_loginBind');
    }


    /**
     * 加入房间
     * @param $rooms
     * @return void
     */
    public function joinRoom($rooms): void
    {
        $rooms = is_string($rooms) || is_int($rooms) ? func_get_args() : $rooms;
        // 统一加上前缀
        $rooms = array_map(fn($room) => $this->appid . '_' . $room, $rooms);
        $this->ws->join($rooms);
    }
}